<template>
  <div id="bookInfo" >
    <div>
      <el-row>
        <el-col :span="6"><el-input placeholder="请输入内容" v-model="bookName"></el-input></el-col>
        <el-col :span="2"><el-button type="primary" icon="el-icon-search" @click="getBookByBookName">搜索</el-button></el-col>
        <el-col :span="4"><el-button type="primary"  @click="addBookDialog">新增书籍</el-button></el-col>
      </el-row>
      <div>
          <el-table
          :data="bookData"
          height="450"
          fit="true"
          style="width: 100%">
            <el-table-column
            prop="createTime"
            label="创建日期">
            </el-table-column>
            <el-table-column
            prop="updateTime"
            label="修改日期">
            </el-table-column>
            <el-table-column
            prop="bookType"
            label="书籍类型">
            </el-table-column>
            <el-table-column
            prop="bookName"
            label="书籍名称">
            </el-table-column>
            <el-table-column
            prop="imageId"
            label="图片">
             <template slot-scope="scope">
                <el-image
                style="width: 100px; height: 100px"
                :src='`http://127.0.0.1:8081/fileController/getImageById?id=${scope.row.imageId}`'
                :fit="fit"></el-image>
              </template>
            </el-table-column>
            <el-table-column
            prop="author"
            label="作者">
            </el-table-column>
            <el-table-column
            prop="count"
            label="数量">
            </el-table-column>
            <el-table-column
            prop="operate"
            label="操作"
            align="center"
            width="300">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="bookDet(scope.row)">查看</el-button>
                <el-button type="primary" size="mini" @click="bookEdit(scope.row)">修改</el-button>
                <el-button type="danger" size="mini" @click="deleteBookById(scope.row.id, scope.row.imageId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
      </div>
      <div style="padding-top:30px ;"></div>
      <!--分页插件 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      <!-- 新增弹窗 -->
      <el-dialog
          :title=title
          :visible.sync="AddBookDialogVisible"
          width="30%"
          center>
          <el-form :model="bookForm" :rules="rules" ref="bookForm" label-width="100px" >
            <el-form-item>
              <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8081/fileController/saveFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            </el-form-item>
            <el-form-item label="书籍名称" prop="bookName">
            <el-input v-model="bookForm.bookName"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="bookType">
              <el-select v-model="bookForm.bookType" placeholder="请选择">
                <el-option
                  v-for="item in bookType"
                  :key="item.id"
                  :label="item.bookType"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="类型" prop="bookType">
              <el-radio v-model="bookForm.sex" label="1">男</el-radio>
              <el-radio v-model="bookForm.sex" label="2">女</el-radio>
            </el-form-item>
            <el-form-item label="书籍作者" prop="author">
            <el-input v-model="bookForm.author"></el-input>
            </el-form-item>
            <el-form-item label="书籍数量" prop="count">
            <el-input v-model="bookForm.count"></el-input>
            </el-form-item>
            <el-form-item label="进货时间" prop="time">
            <el-date-picker
              v-model="bookForm.time"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="submitForm('bookForm')">立即添加</el-button>
            <el-button @click="resetForm('bookForm')">重置</el-button>
            </el-form-item>
          </el-form>
      </el-dialog>
      <!--查看弹窗 -->
      <el-dialog
        title="书籍详情"
        :visible.sync="bookDetailDialogVisible"
        width="30%"
        center>
          <el-form :model="bookDetail"  label-width="100px" >
            <el-form-item label="书籍名称">
            <el-input v-model="bookDetail.bookName" disabled></el-input>
            </el-form-item>
            <el-form-item label="书籍作者">
            <el-input v-model="bookDetail.author" disabled></el-input>
            </el-form-item>
            <el-form-item label="书籍类型">
              <el-input v-model="bookDetail.bookType" disabled></el-input>
            </el-form-item>
            <el-form-item label="书籍数量">
            <el-input v-model="bookDetail.count" disabled></el-input>
            </el-form-item>
          </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      bookType: [],
      AddBookDialogVisible: false,
      bookDetailDialogVisible: false,
      bookData: [],
      imageUrl: '', // 图片地址
      title: '',
      bookForm: {
        id: 0,
        bookName: '',
        bookType: '',
        author: '',
        count: '',
        time: '',
        sex: '1'
      },
      bookDetail: {
        bookName: '',
        bookType: '',
        author: '',
        count: ''
      },
      rules: {
        bookName: [
          { required: true, message: '请输入书籍名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      bookName: '',
      // 分页
      total: 0,
      page: {
        pageNum: 1,
        pageSize: 10
      },
      file: File
    }
  },
  mounted () {
    this.getBookByBookName()
    this.getBookType()
  },
  methods: {
    addBookDialog () {
      this.AddBookDialogVisible = true
      this.title = '新增书籍'
      this.bookForm = {
        id: 0,
        bookName: '',
        author: '',
        bookType: '',
        count: '',
        sex: '2'
      }
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.file = file
      this.imageUrl = URL.createObjectURL(file)
      return false
    },
    // 书籍详情
    bookDet (book) {
      this.bookDetailDialogVisible = true
      this.bookDetail = book
    },
    // 编辑书籍
    bookEdit (book) {
      this.AddBookDialogVisible = true
      this.bookForm = book
      this.imageUrl = 'http://127.0.0.1:8081/fileController/getImageById?id=' + book.imageId
      this.title = '编辑书籍'
    },
    // 分页
    handleSizeChange (val) {
      this.page.pageSize = val
      this.getBookByBookName() // 加载新数据
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      this.page.pageNum = val
      this.getBookByBookName()
      console.log(`当前页: ${val}`)
    },
    // 获取书籍类型
    getBookType () {
      this.$axios.get('/bookType/getAllBookType').then((res) => {
        if (res.data.flag) {
          this.bookType = res.data.obj
        } else {
          this.$message({
            message: res.data.obj,
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 添加书籍
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        console.log(this.bookForm)
        if (valid) {
          var formData = new FormData() // 当前为空
          formData.set('bookName', this.bookForm.bookName)
          formData.set('author', this.bookForm.author)
          formData.set('bookType', 1)
          formData.set('count', this.bookForm.count)
          formData.set('time', this.bookForm.time)
          debugger
          if (this.bookForm.imageId) {
            formData.set('imageId', 0)
          }
          if (this.file.name !== 'File') {
            formData.set('file', this.file, this.file.name)
          }
          if (this.bookForm.id === 0) {
            this.$axios.post('/book/addBook', formData).then((res) => {
              if (res.data.flag) {
                this.$message({
                  message: '恭喜你，添加成功',
                  type: 'success'
                })
                this.AddBookDialogVisible = false
                this.file = File
                this.imageUrl = ''
                this.getBookByBookName()
                this.bookForm = {
                  id: 0,
                  bookName: '',
                  author: '',
                  bookType: '',
                  count: ''
                }
              } else {
                this.$message({
                  message: res.data.obj,
                  type: 'error'
                })
              }
            }).catch(error => {
              console.log(error)
            })
          } else { // 修改
            this.$axios.put('/book/updateBook', formData).then((res) => {
              if (res.data.flag) {
                this.$message({
                  message: '恭喜你，修改成功',
                  type: 'success'
                })
                this.AddBookDialogVisible = false
                this.getBookByBookName()
                this.bookForm = {
                  id: 0,
                  bookName: '',
                  author: '',
                  count: ''
                }
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 查询方法
    getBookByBookName () {
      this.$axios.get('/book/getBookByBookName',
        {
          params: {
            bookName: this.bookName,
            pageNum: this.page.pageNum,
            pageSize: this.page.pageSize
          }
        }).then((res) => {
        if (res.data.flag) {
          this.bookData = res.data.obj.content
          this.total = res.data.obj.total
        } else {
          this.$message({
            message: res.data.obj,
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 删除方法
    deleteBookById (id, imageId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        debugger
        this.$axios.delete('/book/deleteBookById', {
          params: {
            id: id
          }
        }).then(res => {
          if (res.data.flag) {
            this.$message({
              message: '删除成功!',
              type: 'success'
              // message: '删除成功!'
            })
            this.getBookByBookName()
          } else {
            this.$message({
              message: res.data.obj,
              type: 'error'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
<style>
   .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
